package org.jetlinks.pro.assets.impl.terms;

import org.apache.commons.collections4.CollectionUtils;
import org.hswebframework.ezorm.core.param.Term;
import org.hswebframework.ezorm.rdb.metadata.RDBColumnMetadata;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.SqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.term.AbstractTermFragmentBuilder;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collection;

/**
 * 根据资产查询维度数据
 *
 * @author zhouhao
 * @since 1.11
 */
@Component
public class AssetsDimensionTermBuilder extends AbstractTermFragmentBuilder {

    public static final String termType = "assets-dim";

    public AssetsDimensionTermBuilder() {
        super(termType, "根据资产查询维度");
    }

    @Override
    public SqlFragments createFragments(String columnFullName, RDBColumnMetadata column, Term term) {

        AssetsDimensionTerm assetsTerm = AssetsDimensionTerm.of(term);
        boolean not = assetsTerm.isNot();


        PrepareSqlFragments sqlFragments = PrepareSqlFragments.of();
        sqlFragments
            .addSql(not ? "not" : "")
            .addSql("exists(select 1 from s_dimension_assets_bind _bind")
            .addSql("where", columnFullName, "= _bind.target_id")
            .addSql("and _bind.asset_type = ?").addParameter(String.valueOf(assetsTerm.getAssetType()))
            .addSql("and _bind.target_type = ?").addParameter(String.valueOf(assetsTerm.getDimensionType()))
        ;

        Collection<String> assetIds = assetsTerm.getAssetIds();

        if (CollectionUtils.isNotEmpty(assetIds)) {
            String[] assetIdArray = new String[assetIds.size()];
            Arrays.fill(assetIdArray, "?");
            sqlFragments.addSql("and _bind.asset_id in(", String.join(",", assetIdArray), ")")
                        .addParameter((Collection)assetIds);
        }

        if (CollectionUtils.isNotEmpty(assetsTerm.getRelations())) {
            String[] relations = new String[assetsTerm.getRelations().size()];
            Arrays.fill(relations, "?");

            sqlFragments.addSql("and _bind.relation in(", String.join(",", relations), ")")
                        .addParameter((Collection) assetsTerm.getRelations());
        }
        sqlFragments.addSql(")");

        return sqlFragments;
    }
}
